package com.vcg.community.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.vcg.community.dao.ResourceMapper;
import com.vcg.community.dao.UserMapper;
import com.vcg.community.dao.UserrelationMapper;
import com.vcg.community.model.User;
import com.vcg.community.model.Userrelation;

import vc.dubbo.result.DubboResult;

public class UserGetServiceImpl implements UserGetService {

	@Autowired
	private UserMapper usrDao=null;
	@Autowired
	private UserrelationMapper usrRelationDao=null;
	@Autowired
	DataSourceTransactionManager txManager;
	

	public DubboResult<User> getDetail(Integer id) {
		DubboResult<User> resultObject=new DubboResult<User>(0,null);
		try{
			User usrObject=usrDao.selectByPrimaryKey(id);
			resultObject.setResult(usrObject);
		}catch(Exception ex){
			resultObject.setCode(-1);
			resultObject.setCodeError(ex.toString());
		}
		return resultObject;
		
	}

	public DubboResult<List<User>> getFriends(Integer id) {
		DubboResult<List<User>> resultObject=new DubboResult<List<User>>(0,null);
		try{
			List<User> lstUser=usrDao.getFriends(id);
			resultObject.setResult(lstUser);
		}catch(Exception ex){
			resultObject.setCode(-1);
			resultObject.setCodeError(ex.toString());
			
		}
		return resultObject;
	}

	public DubboResult<List<User>> getFollowers(Integer id) {
		DubboResult<List<User>> resultObject=new DubboResult<List<User>>(0,null);
		try{
			List<User> lstUser=usrDao.getFollowers(id);
			resultObject.setResult(lstUser);			
		}catch(Exception ex){
			resultObject.setCode(-1);
			resultObject.setCodeError(ex.toString());			
		}
		return resultObject;
	}
	public DubboResult doFollow(Integer followeeId, Integer followerId){
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

		TransactionStatus status = txManager.getTransaction(def);

		DubboResult resultObject=new DubboResult(0,"",null);
		try{
			Userrelation ur=new Userrelation();
			ur.setFolloweeId(followeeId);
			ur.setFollowerId(followerId);
			usrRelationDao.insert(ur);
		}catch(Exception ex){
			txManager.rollback(status);
			resultObject.setCode(-1);
			resultObject.setCodeError(ex.toString());			
			return resultObject;
		}
		txManager.commit(status);
		return resultObject;		
	}

}
